<?php include "header.php" ?>
		<?php
			$email = "";
			
			if (isset($_SESSION["email"])) {
				echo "You are already logged in. You must log out before you can log in again.";
				require "footer.php";
				die();
			}
			
			if ($_SERVER["REQUEST_METHOD"] == "POST")
			{
				$email = clean_field ($_POST["email"]);
				$password = clean_field ($_POST["password"]);

				$username = 'root';
				$pw = 'ilovesloths13';

				//Connect to the database.
				$con = mysqli_connect ("localhost", $username, $pw, '4350');

				if (mysqli_connect_errno()) {
				  echo "Failed to connect to MySQL: " . mysqli_connect_error();
				}

				//Retrieve salt from database
				$sql = "SELECT salt FROM user WHERE email='$email'";
				$result = mysqli_query($con, $sql);
				while ($row = mysqli_fetch_assoc($result))
					$salt = $row['salt'];

				//Hash password using salt to check with the database
				$hashed_password = hash("sha256", $password . $salt);

				//Checking to see if the account exists with these credentials
				$sql = "SELECT * FROM user WHERE email='$email' and password='$hashed_password'";
				$result=mysqli_query($con, $sql);

				//If it exists, the query returns a result with one row. 
				if (mysqli_num_rows($result) == 1)
				{
					// session_register("email");
					// session_register("password");
					$_SESSION["email"] = $email;

					//Redirects to a login success page.
					header("location:home.php");
				}
				else
					echo "Invalid username or password.";

				mysqli_close();
			}

			function clean_field ($data)
			{
				$data = trim($data);
				$data = stripslashes($data);
				$data = htmlspecialchars($data);
				return $data;
			}

			function hash_pass ($pass)
			{
				$salt = openssl_random_pseudo_bytes(8);
				$hashed = hash("sha256", $password + $salt);
				return $hashed;
			}	
		?>

		<!-- Simple login form -->
		<h2>Customer Login</h2>
		<form method="post" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]);?>">
			Email:<input type="text" name = "email" value="<?php echo $email?>"> <br>
			Password: <input type="password" name="password" value="">
			<input type="submit" name="submit" value="Submit">
		</form>
		<br><br><br>
		Or login as an employee: <a href="employeeLogin.php">Employee Login</a>
<?php include "footer.php" ?>